//
//  AllKindNextDetailViewController.m
//  DongChiDaChiProject1
//
//  Created by lanou3g on 15/10/31.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "AllKindNextDetailViewController.h"
#import "AllNextDetailView.h"
#import "UMSocial.h"
#import "UserCollectData.h"
#import "UserManager.h"
#import "LoginViewController.h"
#import <AVOSCloud/AVOSCloud.h>

@interface AllKindNextDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSMutableArray *yuanLiaoArray;
// 声明一个字典存储每一个原料
@property (nonatomic, strong) NSMutableDictionary *oneYuanLiaoDic;

// 声明一个属性来判断是否已经收藏过
@property (nonatomic, assign) NSInteger isCollection;

// 声明一个属性来判断是否正在收藏
@property (nonatomic, assign) BOOL isEndCollect;

// 声明一个属性来接收userName
@property (nonatomic, strong) NSString *name;

@end

@implementation AllKindNextDetailViewController

- (void)viewDidLoad {
    
  
    
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor magentaColor];
  //  NSLog(@"self.fetchArray = %@, self.allNextModel = %@", self.fetchArray, self.allNextModel);
    // 将model的原料分割成数组
    [self seperateYuanLiao];
    
   
    
    [self.navigationController.navigationBar setTranslucent:NO];
    // 添加导航栏
    [self addBar];
    _isEndCollect = NO;
    // 初值
    _isCollection = 0;
    
}

#pragma mark - 添加导航栏
- (void)addBar
{
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(actionToReturn:)];
    leftItem.tintColor = [UIColor colorWithHue:0.8 saturation:1 brightness:0.7 alpha:1];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(actionToShare:)];
    rightItem.tintColor = [UIColor colorWithHue:0.8 saturation:1 brightness:0.7 alpha:1];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    
}

#pragma mark - 分享的方法

- (void)actionToShare:(UIBarButtonItem *)rightItem
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5637324467e58e7690003055"
                                      shareText:self.allNextModel.title
                                     shareImage:nil
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToQQ, UMShareToRenren, UMShareToTencent, UMShareToDouban,nil]
                                       delegate:nil];
    
    
}

- (void)actionToReturn:(UIBarButtonItem *)leftItem
{
    [self.navigationController popViewControllerAnimated:YES];
}

// 将model的原料分割成数组
- (void)seperateYuanLiao
{
    // 初始化数组
    self.yuanLiaoArray = [NSMutableArray array];
    
    NSArray *tempArray  = [self.allNextModel.ingredients componentsSeparatedByString:@";"];
    NSLog(@"tempArray = %@", tempArray);
    for (NSString *tempString in tempArray) {
        NSArray *yuanSuArray = [tempString componentsSeparatedByString:@","];
        self.oneYuanLiaoDic = [NSMutableDictionary dictionary];
        [self.oneYuanLiaoDic setValue:yuanSuArray[0] forKey:@"yuanLiao"];
        [self.oneYuanLiaoDic setValue:yuanSuArray[1] forKey:@"duoshao"];
        [self.yuanLiaoArray addObject:_oneYuanLiaoDic];
        
    }
    NSLog(@"self.yuanLiaoArray = %@", self.yuanLiaoArray);
    // 构建视图
    [self addView];
}

// 构建视图
- (void)addView
{
    AllNextDetailView *allNextDV = [[AllNextDetailView alloc] initAllNextDetailByFetchArray:self.fetchArray AndModel:self.allNextModel];
    allNextDV.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    allNextDV.shiCaiTableView.dataSource = self;
    allNextDV.shiCaiTableView.delegate = self;
    // 自适应高度的方法
    [allNextDV adjustHeightByYingYang:self.allNextModel.imtro AndCountOfCell:self.yuanLiaoArray.count AndFetchArray:self.fetchArray.count];
    // 给心形button添加方法
    [allNextDV.xinXingButton addTarget:self action:@selector(collection:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:allNextDV];
}

#pragma mark - 收藏按钮
- (void)collection:(UIButton *)button
{
    
    NSLog(@"用户名：%@, 登陆状态:%@", [[UserManager shareUserManagerHandle] getUserName],  [[UserManager shareUserManagerHandle] getIsLogined]);
    self.name = [[UserManager shareUserManagerHandle] getUserName];
    if ([[[UserManager shareUserManagerHandle] getIsLogined] isEqualToString:@"YES"]) {
        // 说明登陆成功
        AVQuery *query = [UserCollectData query];
        //    [query countObjectsInBackgroundWithBlock:^(NSInteger number, NSError *error) {
        //        NSLog(@"数量 = %ld", number);
        //    }];
        
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            for (UserCollectData *tempData in objects) {
                if ([tempData.title isEqualToString:self.allNextModel.title]) {
                    
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"通知" message:@"该界面已经收藏过了，您可以在我的收藏里面查看哦！" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                    [alertView show];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [alertView dismissWithClickedButtonIndex:0 animated:YES];
                    });
                    
                    _isCollection = 1;
                    
                }
            }
            
            if (_isEndCollect == NO) {
                if (_isCollection == 0) {
                    UserCollectData *collectData = [[UserCollectData alloc] init];
                    collectData.albums = self.allNextModel.albums;
                    collectData.burden = self.allNextModel.burden;
                    collectData.imtro = self.allNextModel.imtro;
                    collectData.ingredients = self.allNextModel.ingredients;
                    collectData.title = self.allNextModel.title;
                    collectData.stepArray = self.fetchArray;
                    collectData.userName = self.name;
                    [collectData saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            _isEndCollect = NO;
                            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"通知" message:@"收藏成功！" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                            [alertView show];
                            NSLog(@"收藏成功");
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                [alertView dismissWithClickedButtonIndex:0 animated:YES];
                            });
                        }
                    }];
                    _isEndCollect = YES;
                }
                
            }
            
            
            
            
        }];

    } else {
        // 说明没有登陆成功
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"通知" message:@"该功能需要先登录以后才能使用，您现在要要登录么?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *loginAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           // 跳转到登陆界面
            LoginViewController *loginVC = [[LoginViewController alloc] init];
            [self.navigationController pushViewController:loginVC animated:YES];
        }];
        [alertVC addAction:loginAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
    
  
    
    
    NSLog(@"收藏");
}

#pragma mark - 必须实现的2个方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"self.yuanLiaoArray.count = %ld", (unsigned long)self.yuanLiaoArray.count);
   // return 10;
   return self.yuanLiaoArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"123";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
    }
    if (self.yuanLiaoArray.count > indexPath.row) {
      
    }
//    NSLog(@"yuanliao = %@", [self.yuanLiaoArray[indexPath.row] valueForKey:@"yuanLiao"]);
//    
//    NSLog(@"duoshao = %@", [self.yuanLiaoArray[indexPath.row] valueForKey:@"duoshao"]);
    cell.textLabel.text = [self.yuanLiaoArray[indexPath.row] valueForKey:@"yuanLiao"];
    cell.detailTextLabel.text = [self.yuanLiaoArray[indexPath.row] valueForKey:@"duoshao"];
//    cell.textLabel.text = @"你好";
//    cell.detailTextLabel.text = @"恩";
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
